package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.SecurityUtils;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Region;
import com.ruoyi.system.service.IRegionService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DefCompanyMapper;
import com.ruoyi.system.domain.DefCompany;
import com.ruoyi.system.service.IDefCompanyService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 单位管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-09
 */
@Service
public class DefCompanyServiceImpl implements IDefCompanyService 
{
    private static final Logger log = LoggerFactory.getLogger(DefCompanyServiceImpl.class);
    @Autowired
    private DefCompanyMapper defCompanyMapper;
    @Autowired
    private IRegionService regionService;

    /**
     * 查询单位管理
     * 
     * @param companyId 单位管理主键
     * @return 单位管理
     */
    @Override
    public DefCompany selectDefCompanyByCompanyId(Integer companyId)
    {
        return defCompanyMapper.selectDefCompanyByCompanyId(companyId);
    }

    /**
     * 查询单位管理列表
     * 
     * @param defCompany 单位管理
     * @return 单位管理
     */
    @Override
    public List<DefCompany> selectDefCompanyList(DefCompany defCompany)
    {
        Integer drillId = SecurityUtils.getLoginUser().getDrillId();
        defCompany.setDrillId(drillId);
        defCompany.setCreateBy(SecurityUtils.getUsername());
        return defCompanyMapper.selectDefCompanyList(defCompany);
    }

    /**
     * 新增单位管理
     * 
     * @param defCompany 单位管理
     * @return 结果
     */
    @Override
    public int insertDefCompany(DefCompany defCompany)
    {
        defCompany.setCreateTime(DateUtils.getNowDate());
        return defCompanyMapper.insertDefCompany(defCompany);
    }

    /**
     * 修改单位管理
     * 
     * @param defCompany 单位管理
     * @return 结果
     */
    @Override
    public int updateDefCompany(DefCompany defCompany)
    {
        defCompany.setUpdateTime(DateUtils.getNowDate());
        return defCompanyMapper.updateDefCompany(defCompany);
    }

    /**
     * 批量删除单位管理
     * 
     * @param companyIds 需要删除的单位管理主键
     * @return 结果
     */
    @Override
    public int deleteDefCompanyByCompanyIds(Integer[] companyIds)
    {
        return defCompanyMapper.deleteDefCompanyByCompanyIds(companyIds);
    }

    /**
     * 删除单位管理信息
     * 
     * @param companyId 单位管理主键
     * @return 结果
     */
    @Override
    public int deleteDefCompanyByCompanyId(Integer companyId)
    {
        return defCompanyMapper.deleteDefCompanyByCompanyId(companyId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer importDefCompany(MultipartFile file) {
        try (InputStream fis = file.getInputStream()) {
             XSSFWorkbook workbook = new XSSFWorkbook(fis);
            int count = 0;
            Sheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表
            // 跳过表头，从第2行开始
            for (int i = 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                // 获取每列数据
                String companyName = getCellValue(row.getCell(0));
                if (StringUtils.isEmpty(companyName)) {
                    throw new RuntimeException(String.format("第%d行单位名称为空",  i));
                }
                String province = getCellValue(row.getCell(1));
                if (StringUtils.isEmpty(province)) {
                    throw new RuntimeException(String.format("第%d行省为空",  i));
                }
                String city = getCellValue(row.getCell(2));
                if (StringUtils.isEmpty(city)) {
                    throw new RuntimeException(String.format("第%d行市为空",  i));
                }
                String area = getCellValue(row.getCell(3));
                if (StringUtils.isEmpty(area)) {
                    throw new RuntimeException(String.format("第%d行区县为空",  i));
                }
                String companyAddress = getCellValue(row.getCell(4));
                String companyIndustry = getCellValue(row.getCell(5));
                String companyType = getCellValue(row.getCell(6));
                String remark = getCellValue(row.getCell(7));
                String contacts = getCellValue(row.getCell(8));
                if (StringUtils.isEmpty(contacts)) {
                    throw new RuntimeException(String.format("第%d行联系人为空",  i));
                }
                String phoneNo = getCellValue(row.getCell(9));
                if (StringUtils.isEmpty(phoneNo)) {
                    throw new RuntimeException(String.format("第%d行联系电话为空",  i));
                }
                // 创建 Company 实体
                DefCompany company = new DefCompany();
                company.setCompanyName(companyName);
                List<DefCompany> defCompanies = selectDefCompanyList(company);
                if (!CollectionUtils.isEmpty(defCompanies)) {
                    throw new RuntimeException(String.format("第%d行%s已存在",  i,companyName));
                }
                Region region = new Region();
                region.setName(province);
                List<Region> regions = regionService.selectRegionList(region);
                if (!CollectionUtils.isEmpty(regions)) {
                    company.setProvince(String.valueOf(regions.get(0).getId()));
                }
                company.setCity(city);
                region.setName(city);
                regions = regionService.selectRegionList(region);
                if (!CollectionUtils.isEmpty(regions)) {
                    company.setCity(String.valueOf(regions.get(0).getId()));
                }
                company.setArea(area);
                region.setName(area);
                regions = regionService.selectRegionList(region);
                if (!CollectionUtils.isEmpty(regions)) {
                    company.setArea(String.valueOf(regions.get(0).getId()));
                }
                company.setCompanyAddress(companyAddress);
                company.setCompanyIndustry(companyIndustry);
                company.setCompanyType(companyType);
                company.setRemark(remark);
                company.setContacts(contacts);
                company.setPhoneNo(phoneNo);
                company.setCreateTime(new Date());  // 设置创建时间
                count += insertDefCompany(company);
            }
            return count;
        } catch (Exception e) {
            log.error("导入单位信息出错", e);
            throw new RuntimeException("导入单位信息出错,请检查模板后重试");
        }
    }

    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }
}
